"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import Input from "@/components/custom-ui/input";
import { Loader, MailIcon } from "lucide-react";
import { ForgotFormData, ForgotSchema } from "@/schemas/auth";
import { useMutation } from "@tanstack/react-query";
import { forgotAction } from "@/actions/auth";
import { useTranslations } from "next-intl";

export default function ForgotForm() {
  const t = useTranslations("authPages");
  const tZod = useTranslations("zod");
  const form = useForm<ForgotFormData>({
    resolver: zodResolver(ForgotSchema(tZod)),
    defaultValues: {
      email: "",
    },
  });
  const mutation = useMutation({
    mutationFn: forgotAction,
    onSuccess: (data) => {
      if (data.success) {
        toast.success(data.success);
      }
      if (data.error) {
        toast.error(data.error);
      }
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });

  const { mutate, isPending } = mutation;
  const onSubmit = (values: ForgotFormData) => mutate(values);
  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="w-full space-y-6">
        <FormField
          control={form.control}
          name="email"
          render={({ field }) => (
            <FormItem>
              <FormLabel className="text-muted-foreground">{t("email")}</FormLabel>
              <FormControl>
                <Input
                  className="h-12 flex items-center"
                  placeholder="example@example.com"
                  {...field}
                  startIcon={<div className="w-10 flex justify-center"><MailIcon className="h-4 w-4" /></div>}
                  autoComplete="email"
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <Button
          className="w-full h-12 cursor-pointer select-none"
          type="submit"
          disabled={isPending}
        >
          {isPending ? <Loader /> : null}
          {t("sendEmail")}
        </Button>
      </form>
    </Form>
  );
}
